package com.jianbo.proxy.core;

import java.util.Map;

import org.smartboot.http.server.HttpRequest;

import com.jianbo.proxy.conf.ArgsConf;
import com.jianbo.proxy.conf.jsconfig.ApiConfig;
import com.jianbo.proxy.entity.HttpResponseMiddle;
import com.jianbo.proxy.service.FilterWebService;
import com.jianbo.proxy.util.ByteUtil;
import com.jianbo.proxy.util.Debug;
import com.jianbo.proxy.util.FileUtil;
import com.jianbo.proxy.util.JsUtil;
import com.jianbo.proxy.util.ThreadDataUtil;

public class ApiWeb implements Web {

    @Override
    public boolean handle(String path, HttpRequest request, HttpResponseMiddle response) throws Exception {

        Map<String, String> conf = apiConfig.getApiMap();
        if(conf.containsKey(path)) {

            ArgsConf argsConfig = ArgsConf.getInstance();
            String apiFile = argsConfig.getConfDir() + conf.get(path);

            if(FileUtil.exist(apiFile)) {
                String jsCode = FileUtil.readString(apiFile);
                // 加载js文件，获得js文件输出，下入到 response 中
                jsCode = FilterWebService.jsCode(jsCode);
                
                ThreadDataUtil.put("url", path);

                JsUtil.runFull(jsCode);

                String result = ThreadDataUtil.get("code");
                
                ThreadDataUtil.clear();
                
                response.write(ByteUtil.bytes(result));

                return true;
            }
        }
        return false;
    }

    ApiConfig apiConfig;
    public void setApiConf(ApiConfig apiConfig) {
        this.apiConfig = apiConfig;
    }
    
}
